package com.hydl.power.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hydl.power.aop.annotation.LogAnnotation;
import com.hydl.power.mapper.CityMapper;
import com.hydl.power.mapper.InspectionOrderMapper;
import com.hydl.power.mapper.MaintainerMapper;
import com.hydl.power.mapper.PowerRoomMapper;
import com.hydl.power.pojo.*;
import com.hydl.power.service.*;
import com.hydl.power.utils.*;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "InspectionplanController",tags = "巡查列表")
@RestController
@RequestMapping("/inspectionplan")
@CrossOrigin
public class InspectionplanController {

    @Autowired
    private InspectionplanService inspectionplanService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private PowerRoomMapper powerRoomMapper;
    @Autowired
    private MaintainerMapper maintainerMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private InspectionOrderService inspectionOrderService;

    @Autowired
    private InspectionOrderMapper inspectionOrderMapper;

    @Autowired
    private InspectionContentService inspectionContentService;


    @ApiOperation("查询巡检内容")
    @PostMapping("getInspectionContent")
    public Resp getInspectionContent(){
        List<InspectionContent> inspectionContent = inspectionContentService.getInspectionContent();
        return Resp.success(inspectionContent);
    }


  @ApiOperation(value = "提交巡检结果", produces = "application/json")
  @PostMapping("addInspectionResult")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "projectName", value = "项目name", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "poweroomId", value = "配电房id", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "powerroomName", value = "配电房名字", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "result", value = "巡检内容", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "maintainerId", value = "巡查人员id", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "maintainerName", value = "巡查人员name", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "maintainerPhone", value = "巡查人员电话", dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "maintainerImage", value = "图片路径", dataType = "String"),
  })
  public Resp addInspectionResult(String projectId,String projectName,String poweroomId,String powerroomName,String result,String maintainerId,String maintainerName,String maintainerPhone,String maintainerImage,String longitude,String dimensionality){
      int i= inspectionOrderService.insertSelective(projectId,projectName,poweroomId,powerroomName,result,maintainerId,maintainerName,maintainerPhone,maintainerImage,longitude,dimensionality);
    if(i > 0){
      return Resp.success("提交成功");
    }
    return Resp.fail("提交失败");
  }


    @ApiOperation("客户查看巡检结果")
    @PostMapping("getInspectionResult")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orderId", value = "巡检计划id", dataType = "Integer"),
    })
    public Resp getInspectionResult(Integer id){
        List<InspectionContent> inspectionResult = inspectionContentService.getInspectionResult(id);
        return Resp.success(inspectionResult);
    }


    //@LogAnnotation(module = "巡查列表",description = "按条件查询计划")
    @ApiOperation(value = "按条件查询计划")
    @PostMapping(value = "/selectByCondition")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "显示个数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "taskType", value = "任务类型", required = false, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "taskStatus", value = "执行状态", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "maintainerId", value = "维护人员id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "startTime", value = "开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "endTime", value = "结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "token", value = "token", required = false, dataType = "String")
    })
    public Resp<PageInfo<Inspectionplan>> selectByCondition(@RequestParam(required = false )Integer pageNum,
                                                        @RequestParam(required = false )Integer pageSize,
                                                        @RequestParam(required = false) String taskType,
                                                        @RequestParam(required = false) String taskStatus,
                                                        @RequestParam(required = false) String maintainerId,
                                                        @RequestParam(required = false) String startTime,
                                                        @RequestParam(required = false) String endTime,
                                                            @RequestParam(required = false) String token){
/*        if(StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
            return Resp.fail("参数不能为空");
        }*/
        PageInfo<Inspectionplan>  list=inspectionplanService.selectByCondition(pageNum,pageSize,taskType,taskStatus, maintainerId,  startTime,  endTime,token);
        if(list.getList().isEmpty() || list == null){
            return Resp.success("未查询到信息");
        }
        return Resp.success(list);
    }


    //@LogAnnotation(module = "巡查列表",description = "增加计划")
    @ApiOperation(value = "增加计划")
    @PostMapping(value = "/addPlan")
    @Transactional
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskname", value = "任务名称", required = false, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "tasktype", value = "任务类型1巡查 2检修 3试验", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "taskcontent", value = "任务内容", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "tasktime", value = "制定执行时间", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "taskstatus", value = "执行状态0 正常 1 失效", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "roomid", value = "配电房id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "maintainerid", value = "维护人员id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "runmode", value = "0单次，1每月", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "cityId", value = "区域id", required = false, dataType = "String"),
    })
    public Resp addPlan(String taskname,String tasktype,String taskcontent,String tasktime,
                        String taskstatus ,String roomid ,String maintainerid,String projectId ,String runmode,String cityId ){
        if(StringUtils.isBlank(taskname) || StringUtils.isBlank(tasktype) || StringUtils.isBlank(taskcontent) || StringUtils.isBlank(tasktime) || StringUtils.isBlank(taskstatus) || StringUtils.isBlank(roomid)
                || StringUtils.isBlank(maintainerid) || StringUtils.isBlank(runmode)
                 || StringUtils.isBlank(projectId)  || StringUtils.isBlank(cityId)){
            return Resp.fail("参数不能为空");
        }
        Project project=projectService.queryProjectByProId(projectId);
        if(project==null){
            return Resp.fail("输入的项目编码有误");
        }
        PowerRoom PowerRoom=powerRoomMapper.selectByRoomId(roomid);
        if(PowerRoom==null){
            return Resp.fail("输入的配电房编码有误");
        }
        Maintainer Maintainer=maintainerMapper.selectById1(maintainerid);
        if(Maintainer==null){
            return Resp.fail("输入的运维编码有误");
        }
        City city=cityMapper.queryCityByCityId(cityId);
        int flag = inspectionplanService.addPlan(taskname,tasktype,taskcontent,tasktime,taskstatus,PowerRoom.getRoomName(),roomid,Maintainer.getName(),maintainerid,projectId,project.getProjectName(),runmode,cityId,city.getCityName());
        String[] str = tasktime.split(",");

        Map<String, String> map = new HashMap<String, String>();
        map.put("roomname", PowerRoom.getRoomName());

        if (flag == 1){
          for (String s : str) {
            map.put("task", s);
            String data = JSONObject.toJSONString(map);
            SmsUtils.sendSms(Maintainer.getPhone(),"合一电力","SMS_197891554",data);		// 发送短信的手机号、短信内容、短信定时时间（可为空）
          }
            return Resp.success("Success");
        }else{
            return Resp.fail("添加失败");
        }
    }

    @LogAnnotation(module = "巡查列表",description = "删除计划")
    @ApiOperation(value = "删除计划")
    @PostMapping(value = "/delectPlan")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tid", value = "任务id", required = false, dataType = "Integer"),
    })
    public Resp delectPlan(Integer tid){

        return inspectionplanService.delectPlan(tid);
    }


    @LogAnnotation(module = "巡查列表",description = "修改计划")
    @ApiOperation(value = "修改计划")
    @PostMapping(value = "/updatePlan")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskname", value = "任务名称", required = false, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "tasktype", value = "任务类型1巡查 2检修 3试验", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "taskcontent", value = "任务内容", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "tasktime", value = "制定执行时间", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "taskstatus", value = "执行状态0 正常 1 失效", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "roomid", value = "配电房id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "maintainerid", value = "维护人员id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "runmode", value = "0单次，1每月", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "cityId", value = "区域id", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "tid", value = "tid", required = false, dataType = "Integer",defaultValue = "1")
    })
    public Resp updatePlan(String taskname,String tasktype,String taskcontent,String tasktime,
                           String taskstatus ,String roomid ,String maintainerid,String projectId ,String runmode,String cityId,Integer tid){
        if(StringUtils.isBlank(taskname) || StringUtils.isBlank(tasktype) || StringUtils.isBlank(taskcontent) || StringUtils.isBlank(tasktime) || StringUtils.isBlank(taskstatus) || StringUtils.isBlank(roomid)
                || StringUtils.isBlank(maintainerid) || StringUtils.isBlank(runmode)
                || StringUtils.isBlank(projectId)  || StringUtils.isBlank(cityId)){
            return Resp.fail("参数不能为空");
        }
        Project project=projectService.queryProjectByProId(projectId);
        if(project==null){
            return Resp.fail("输入的项目编码有误");
        }
        PowerRoom PowerRoom=powerRoomMapper.selectByRoomId(roomid);
        if(PowerRoom==null){
            return Resp.fail("输入的配电房编码有误");
        }
        Maintainer Maintainer=maintainerMapper.selectById1(maintainerid);
        if(Maintainer==null){
            return Resp.fail("输入的运维编码有误");
        }
        City city=cityMapper.queryCityByCityId(cityId);

        int flag = inspectionplanService.updateByPrimaryKeySelective(taskname,tasktype,taskcontent,tasktime,taskstatus,Maintainer.getName(),maintainerid,PowerRoom.getRoomName(),roomid,
                runmode,project.getProjectId(),project.getProjectName(),city.getCityId(),city.getCityName(),tid);

        Map<String, String> map = new HashMap<String, String>();
        map.put("roomname", PowerRoom.getRoomName());
        if(runmode.equals("1")){
            tasktime="每月"+tasktime+"日";
            map.put("str", tasktime);
        }else {
            map.put("str", tasktime);
        }
        String data = JSONObject.toJSONString(map);
        if (flag == 1){
            SmsUtils.sendSms(Maintainer.getPhone(),"合一电力","SMS_198916405",data);		// 发送短信的手机号、短信内容、短信定时时间（可为空）
            return Resp.success("Success");
        }else{
            return Resp.fail("修改失败");
        }
    }


    // @LogAnnotation(module = "巡查列表",description = "根据id查询计划")
    @ApiOperation(value = "根据id查询计划")
    @PostMapping(value = "/queryplanById")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tid", value = "任务id", required = false, dataType = "Integer"),
    })
    public Resp queryplanById(Integer tid){

        return Resp.success(inspectionplanService.queryplanById(tid));
    }

  // @LogAnnotation(module = "巡查列表",description = "根据id查询计划")
  @ApiOperation(value = "查询待确认巡查工单")
  @PostMapping(value = "/queryStatus")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query", name = "token", value = "token", required = false, dataType = "String"),
  })
  public Resp queryStatus(String token){
    List<InspectionOrder> list = inspectionplanService.queryStatus(token);
    if(list.size() == 0 || list == null){
      return Resp.success("未查询到数据",null,null);
    }
    return Resp.success(list);
  }

  @ApiOperation(value = "用户签名确认")
  @PostMapping(value = "/updateUserSubmitImage")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query", name = "inspectionReport", value = "inspectionReport", required = false, dataType = "String"),
    @ApiImplicitParam(paramType = "query", name = "inspectionPlanId", value = "inspectionPlanId", required = false, dataType = "String"),
  })
  public Resp updateUserSubmitImage(String inspectionReport,String inspectionPlanId){
    int list = inspectionContentService.updateUserSubmitImage( inspectionReport,inspectionPlanId);
    if(list == 0 ){
      return Resp.fail("确认失败");
    }
    return Resp.success("用户已确认",null,null);
  }


    @ApiOperation(value = "巡查工单列表")
    @PostMapping(value = "/queryInspectionOrder")
    @ApiImplicitParams({
      @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页码", required = true, dataType = "String"),
      @ApiImplicitParam(paramType = "query", name = "pageSize", value = "显示个数", required = true, dataType = "String"),
      @ApiImplicitParam(paramType = "query", name = "startTime", value = "开始时间", required = false, dataType = "String"),
      @ApiImplicitParam(paramType = "query", name = "endTime", value = "结束时间", required = false, dataType = "String"),
      @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", required = false, dataType = "String")
    })
    public Resp<PageInfo<Inspectionplan>> queryInspectionOrder(Integer pageNum, Integer pageSize,String startTime, String endTime, String projectId){
      PageInfo<InspectionOrder>  list=inspectionOrderService.queryInspectionOrder(pageNum,pageSize,startTime,endTime,projectId);
      if(list.getSize()==0){
        return Resp.success("未查询到信息");
      }
      return Resp.success(list);
    }

  //   @LogAnnotation(module = "设备电力数据导出",description = "电力数据导出")
  @ApiOperation("巡检记录导出")
  @GetMapping("/queryPowerDataExport")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query", name = "InspectionPlanId", value = "id",defaultValue = "",dataType = "Integer"),
  })
  public void queryPowerDataExport(Integer id,HttpServletResponse response)throws Exception{
    List<InspectionContent> inspectionResult = inspectionContentService.getInspectionResult(id);
    InspectionOrder inspectionOrder=inspectionOrderMapper.getInspectionResultByOrderId(id);
    List<InspectionContent> list = new ArrayList();
    //创建全局变量 colList为列集合，list1为值得集合
    List colList = new ArrayList<>();
    Map<String, Object> valMap = new HashMap<String, Object>();
    Map<String, Object> valMap1 = new HashMap<String, Object>();
    Map<String, Object> valMap2 = new HashMap<String, Object>();
    Map<String, Object> valMap3 = new HashMap<String, Object>();
    List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();



    valMap1.put("option",inspectionOrder.getProjectName());
    valMap1.put("value",inspectionOrder.getIPQCNAME());
    valMap1.put("result",inspectionOrder.getIPQCIphone());
    list1.add(valMap1);

    valMap2.put("option","项目联系人");
    valMap2.put("value","职务");
    valMap2.put("result","巡查时间");
    list1.add(valMap2);

    valMap3.put("option",inspectionOrder.getMaintainerName());
    valMap3.put("value"," ");
    valMap3.put("result",inspectionOrder.getCreateTime());
    list1.add(valMap3);


    valMap.put("option","巡检项目");
    valMap.put("value","检查结果");
    valMap.put("result","备注(√:无问题，×：有问题)");
    list1.add(valMap);

    for (InspectionContent inspectionContent : inspectionResult) {
      list.add(inspectionContent);
      for (Object o : inspectionContent.getList()) {
        o=(InspectionContent)o;
        if(((InspectionContent) o).getValue().equals("1")){
            ((InspectionContent) o).setValue("√");
        }else {
          ((InspectionContent) o).setValue("×");
        }
        list.add(((InspectionContent) o));
      }
    }

    for (Object o : list) {
      //清空map
      valMap = new HashMap<String, Object>();
      //清空列得值
      colList = new ArrayList<>();
      o=(InspectionContent)o;
      //添加设备名称列 保证下方循环时不为空
      ExcelExportEntity colEntity = new ExcelExportEntity("项目","option");
      colEntity.setNeedMerge(true);
      colEntity.setWidth(40);
      colList.add(colEntity);
      if(((InspectionContent) o).getValue()==null){
        valMap.put("option",((InspectionContent) o).getOption());
      }else {
        valMap.put("option",((InspectionContent) o).getOption());
      }

      //添加采集时间列
      colEntity = new ExcelExportEntity("巡检人","value");
      colEntity.setNeedMerge(true);
      colEntity.setWidth(9);
      colList.add(colEntity);
      valMap.put("value",((InspectionContent) o).getValue());

      colEntity = new ExcelExportEntity("联系电话","result");
      colEntity.setNeedMerge(true);
      colEntity.setWidth(40);
      colList.add(colEntity);
      valMap.put("result",((InspectionContent) o).getContent());
      list1.add(valMap);
    }

    System.out.println(colList);
    System.out.println(list1);
    ExportParams exportParams = new ExportParams("配电房巡检记录", "巡检项目", ExcelType.XSSF);
    //引用样式
    exportParams.setStyle(ExcelStyleUtil.class);
    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, colList,list1);

    //获取sheetAt对象，这里一个sheetAt所以角标是0
    Sheet sheetAt = workbook.getSheetAt(0);
    // 表格行数
    int lastRowNum = sheetAt.getLastRowNum();

    // 获取列数
    int physicalNumberOfCells = sheetAt.getRow(0).getPhysicalNumberOfCells();

    //开始遍历单元格并进行判断是否渲染
    for (int i = 1 ; i <= lastRowNum ; i++) {
      //获取每行对象
      Row row = sheetAt.getRow(i);
      for (int j = 0; j < physicalNumberOfCells; j++) {
        //获取单元格对象
        Cell cell = row.getCell(j) ;
        String str = cell.getStringCellValue().trim();
        System.out.println(str);
        //获取单元格样式对象
        CellStyle cellStyle = workbook.createCellStyle();
        //获取单元格内容对象
        Font font = workbook.createFont();

        //一定要装入 样式中才会生效
        cellStyle.setFont(font);

        //获取当前单元格 中的value

          if (str.contains("内容") ){
            //背景色
            cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            font.setBold(true);
            //水平居中
            //cellStyle.setAlignment(HorizontalAlignment.CENTER);
        }
        if(str.equals("备注")){
          //水平居中
          cellStyle.setAlignment(HorizontalAlignment.CENTER);
        }
        //下边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        //左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        //上边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        //右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        //上下居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置自动换行
        cellStyle.setWrapText(true);
        //字体样式
        font.setFontName("宋体");
        //字体大小
        font.setFontHeightInPoints((short)10);
        cell.setCellStyle(cellStyle);
      }
    }
    OutputStream outstream = response.getOutputStream();
    response.reset();
    response.setHeader("Content-disposition", "attachment; filename=" + new String("巡检内容".getBytes(),"iso-8859-1") + ".xls");
    response.setContentType("application/x-download");
    workbook.write(outstream);
    outstream.close();
  }
}
